import Vue from 'vue';
import Vuex from 'vuex';
import axios from "axios";
import VuexPersist from 'vuex-persist';
Vue.use(Vuex);
const vuexLocalStorage = new VuexPersist({
    key: 'vuex',
    storage: window.sessionStorage,
});


import manageVuex from "./manageVuex/manageVuex";
import modelVuex from "./modelVuex/modelVuex";
import monitorVuex from "./monitorVuex/monitorVuex";
import processingVuex from "./processingVuex/processingVuex";
import qualityCheckVuex from "./qualityCheckVuex/qualityCheckVuex";
import taskManageVuex from "./taskManageVuex/taskManageVuex";
import indexApi from "../globalApi/indexApi";

const store = new Vuex.Store({
    plugins: [vuexLocalStorage.plugin],
    state: { //管理变量 只读属性 由store.state.xx读取       
        user: {}, //JSON.parse(sessionStorage.getItem(key)) || {},
        isLogin: false,
        permissionData: [], //权限
        ProductionLineRetrieval: "nosearch", //处理加工界面和质检界面的检索框的显示
        navigationShow: "", //点击左侧树导航栏高亮显示
        lastRoute: "", //记录游客登录之前看的页面路由
        // 导航图标的信息  start
        homeIcon: "",
        firstTitle: "",
        secondTitle: "",
        imgSty: "",
        secondTitleStatious: "",
        // end
        chunk: 0, //分块号
        chunks: 0, //分片的总数
        uploadBigId: "", //大文件上传的id
        //控制左侧栏初次加载样式处理加工
        lastLeftPathStyleData: {
            secondLevel: "",
            thirdLevelId: ""
        },
        leftPathStyleData: {
            secondLevel: "",
            thirdLevelId: ""
        },
        //监控页面高度或者宽度的变化
        screenWidth: document.documentElement.clientWidth,
        screenHeight: document.documentElement.clientHeight,
        colorPick: "#2d8cf0",
        colorPickThree: "#2d8cf0",
        colorPickSeven: "#2d8cf0",
        collectTreeNode: []//记录文件目录整棵zTree树

    },
    mutations: { //操作变量 由 store.commit('xx')触发
        setStorage(state, value) {
            state.user = value;
            /*userName: result.userData.userName,
            token: result.token,
            department: result.userData.organizationName,
            nickName: result.userData.nickName,
            roleName: result.userData.roleName,*/
            window.sessionStorage.setItem("user", value ? value.userName : "");
            window.sessionStorage.setItem("mobile", value ? value.mobile : "");
            window.sessionStorage.setItem("nickName", value ? value.nickName : "");
            window.sessionStorage.setItem("PIECloud-Token", value ? value.token : "");
            window.sessionStorage.setItem("userId", value ? value.userId : "");
            if (state.user != null) {
                state.isLogin = true;
            }
            store.commit('setSystemPermissions') //存储权限信息
        },
        removeStorage(state) {
            state.user = null;
            window.sessionStorage.removeItem("user");
            window.sessionStorage.removeItem("PIECloud-Token");
            window.sessionStorage.removeItem("userId");
            window.sessionStorage.removeItem("nickName");
            state.isLogin = false;
            state.permissionData = null;
        },
        setRoute(state, value) {
            state.lastRoute = value;
        },
        removeRoute(state) {
            state.lastRoute = '';
        },

        //获取权限//后台ajax获取系统菜单等所有权限
        setSystemPermissions(state) {
            let path = indexApi.homeLoginOthers.permissionPath;

            let param = { systemId: systemId }
            let token = window.sessionStorage.getItem("PIECloud-Token");
            var acookie = document.cookie.split("; ");
            let getck = (sname) => {//获取单个cookies
                for (var i = 0; i < acookie.length; i++) {
                    var arr = acookie[i].split("=");
                    if (sname == arr[0]) {
                        if (arr.length > 1)
                            return arr[1];
                        else
                            return "";
                    }
                }
                return "";
            }
            let xcookie = getck("engine-token");

            $.ajax({
                type: "GET",
                async: false, // fasle同步，true异步  
                headers: {
                    Authorization: token ? token : null,
                    "x-token": `${xcookie}`
                },
                contentType: "application/json;charset=UTF-8",
                url: path,
                data: param,
                success: function (res) {
                    state.permissionData = res.data;
                },
                error: function (e) {
                    console.log(e.responseText);
                }
            });
        },
        //控制左侧导航的搜索是否显示
        setHeaderSation(state, ProductionLineRetrieval) { //nosearch 隐藏 yessearch 显示
            state.ProductionLineRetrieval = ProductionLineRetrieval;
        },
        setUploadBigId(state, value) {
            state.uploadBigId = value;
        },
        //修改一二级菜单id
        changeLeftPathStyleData(state, {
            secondLevel,
            thirdLevelId
        }) {
            state.lastLeftPathStyleData.secondLevel = state.leftPathStyleData.secondLevel
            state.lastLeftPathStyleData.thirdLevelId = state.leftPathStyleData.thirdLevelId

            state.leftPathStyleData.secondLevel = secondLevel;
            state.leftPathStyleData.thirdLevelId = thirdLevelId;
        },
        //换肤功能
        changeColorThem(state, value) {
            state.colorPick = value.val.toString();
            state.colorPickThree = value.three.toString();
            state.colorPickSeven = value.seven.toString();
        },
        //初始化整棵zTree树
        setCollectTreeNode(state, value) {
            state.collectTreeNode = value
        }
    },
    actions: {
        login({
            commit
        }, user) {
            commit("setStorage", user)
        },
        logout({
            commit
        }) {
            commit("removeStorage")
        },
        setPermission({
            commit
        }) {
            commit("setSystemPermissions")
        },
        setRoute({
            commit
        }, value) {
            commit("setRoute", value)
        },
        removeRoute({
            commit
        }) {
            commit("removeRoute")
        }
    },
    getters: { //计算变量 通过store.getters.xx访问
        getUser: function (state) {
            // if (!state.user)   // user = {token: "", userName: "", userId: "",}
            //     state.user = JSON.parse(sessionStorage.getItem(key))
            return state.user
        },
        getSystemPermissions: function (state) {
            return state.permissionData;
        },
        getRoute: function (state) {
            return state.lastRoute;
        },
        // 图标和标题的修改
        getHomeIcon: function (state) {
            let path = indexApi.homeLoginOthers.getByAppId + systemId;
            $.ajax({
                type: "GET",
                async: false, // fasle同步，true异步
                headers: {
                    Authorization: state.user != null ? state.user.token : ""
                },
                contentType: "application/json;charset=UTF-8",
                url: path,
                // data: param,
                success: function (res) {
                    state.homeIcon = res.data.homeImage;
                    state.firstTitle = res.data.firstTitle;
                    state.secondTitle = res.data.secondTitle;
                    state.imgSty = "width:" + res.data.homeWidth + "px;height:" + res.data.homeHeight + "px";
                    //1 --二级标题显示  2 -- 二级标题隐藏
                    if (res.data.isShow == 1) {
                        state.secondTitleStatious = true
                    } else {
                        state.secondTitleStatious = false
                    }
                },
                error: function (e) {
                    console.log(e.responseText);
                }
            });
        },
        // 修改导航显示状态
        addHeaderClass() { },
        // 移除导航显示状态
        removeHeaderClass() { },
        //权限中提出下拉的权限
        getBtnProcessPriority(state) {
            if (!state.permissionData) {
                return {
                    enableFlag: '1',
                }
            }
            let data = state.permissionData.find((item) => {
                return item.code == "Btn_Process_Priority";
            });
            if (data) {
                return data;
            } else {
                return {
                    enableFlag: '1',
                }
            }
        },
        //返回整棵zTree树
        getCollectTreeNode(state) {
            return state.collectTreeNode
        }


    },
    //模块vuex
    modules: {
        manageVuex,
        modelVuex,
        monitorVuex,
        processingVuex,
        qualityCheckVuex,
        taskManageVuex
    }
});

export default store;